package com.tianji.jd.data.aop;

import com.tianji.jd.data.aop.annotation.UseDataSource;
import com.tianji.jd.data.utile.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Description: 数据源切面类
 *
 * @author chenjia
 * @version 1.0
 * @date 2024/11/12 13:56
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Around("@annotation(com.tianji.jd.data.aop.annotation.UseDataSource)")
    public Object switchDataSource(ProceedingJoinPoint point) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        // 获取注解
        UseDataSource useDataSource = method.getAnnotation(UseDataSource.class);
        String dataSourceKey = useDataSource.value();
        DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);
        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceKey();
        }
    }

}
